import React, {
  Component,
  useState,
  useEffect,
} from "react";
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
} from "react-native";
import Content from "../../components/content/content";
import styles from "./add-account-sheet";

import * as api from "../../api";
import * as utils from "../../utils";

export default function AddAccount(props) {
  const {
    type,
    cb
  } = props.navigation.state.params;
  const [nick, setNick] = useState('');
  const [url, setUrl] = useState('');

  getNick = (value) => {
    setNick(value);
  }

  getUrl = (value) => {
    setUrl(value);
  }

  submit = () => {
    if (nick === '' || url === '') {
      global.showToast('昵称或者主页链接不能为空');
      return;
    }
    if (!utils.checkUrl(url)) {
      global.showToast('主页链接格式不正确');
      return;
    }
    global.showLoading();
    api.addAccount({
      account: nick,
      homepage_url: url,
      platform: type,
    }).then(res => {
      global.showToast('提交成功');
      setNick('');
      setUrl('');
      cb([{
        account: nick,
        homepage_url: url,
      }]);
    }).catch(rej => {
      global.showToast(rej);
    }).finally(() => {
      global.closeLoading();
    });
  };

  return (
    <Content>
			<View style={styles.content}>
        <View style={[styles.input, styles.marginTop20]}>
          <View style={styles.inputTitle}>
            <Text>昵称: </Text>
          </View>
          <View style={styles.inputText}>
            <TextInput maxLength={32} 
               autoCapitalize="none" 
               placeholder="请输入昵称" 
               style={styles.inputTextC}
               onChangeText={getNick}
               value={nick}
            />
          </View>
        </View>

        <View style={[styles.input, styles.marginTop20]}>
          <View style={styles.inputTitle}>
            <Text>主页链接: </Text>
          </View>
          <View style={styles.inputText}>
            <TextInput maxLength={32} 
              autoCapitalize="none" 
              placeholder="请输入主页链接" 
              style={styles.inputTextC}
              onChangeText={getUrl}
              value={url}
            />
          </View>
        </View>

        <View style={[styles.marginTop20, styles.buttonContent]}>
          <TouchableOpacity onPress={submit} style={styles.button}>
            <Text style={styles.buttonText}>提交</Text>
          </TouchableOpacity>
        </View>
      </View>
		</Content>
  )
}